package com.xiegang.serviceMap.remote;

import com.xiegang.internalcommon.constant.AmapConfigConstants;
import com.xiegang.internalcommon.dto.PointDTO;
import com.xiegang.internalcommon.dto.ResponseResult;
import com.xiegang.internalcommon.request.PointRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author xieGang
 * @description
 * @date 2023/4/5 13:03
 **/

@Service
@Slf4j
public class PointClient {

    @Value("${Amap.key}")
    private String key;

    @Value("${Amap.sid}")
    private String sid;

    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult upload(PointRequest pointRequest) {

        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.POINT_UPLOAD_URL);
        url.append("?");
        url.append("key=");
        url.append(key);
        url.append("&");
        url.append("sid=");
        url.append(sid);
        url.append("&");
        url.append("tid=");
        url.append(pointRequest.getTid());
        url.append("&");
        url.append("trid=");
        url.append(pointRequest.getTrid());
        url.append("&");
        url.append("points=");
        /**
         * [{"location":"116.45,39.91","locatetime":1680589051472}]
         *
         * https://tsapi.amap.com/v1/track/point/upload?key=d5df9c3cb246a0dff2969b5ba9e336eb&tid=661825010&sid=915098&trid=20&points=[{"location":"116.45,39.91","locatetime":1680589051472}]
         */
        url.append("%5B");
        for (PointDTO p : pointRequest.getPoints()) {
            String location = p.getLocation();
            String locatetime = p.getLocatetime();
            url.append("%7B");

            url.append("%22location%22");
            url.append("%3A");
            url.append("%22"+location+"%22");

            url.append("%2C");

            url.append("%22locatetime%22");
            url.append("%3A");
            url.append(locatetime);

            url.append("%7D");
        }
        url.append("%5D");


        log.info("高德地图请求："+url.toString());
        ResponseEntity<String> forEntity = restTemplate.postForEntity(URI.create(url.toString()), null, String.class);
        log.info("高德地图响应："+forEntity.getBody());

        return ResponseResult.success();
    }
}
